<template>
  <div>
    <a-modal
      v-model="visible"
      :confirmLoading="confirmLoading"
      v-bind="modelAttrs"
      @ok="ok"
      @cancel="cancel"
    >
      <template v-if="isParamError">
        <div class="empty-wrap">
          <a-empty :description="description" />
        </div>
      </template>
      <template v-else>
        <a-form ref="myform" :form="formOpinion">
          <k-form
            ref="formRenderRef"
            :form="formOpinion"
            :isView="false"
            :drawingList="drawingList"
          >
          </k-form>
        </a-form>
      </template>
    </a-modal>
  </div>
</template>

<script>
import KForm from "@/components/TopVUI/k-form-design/packages/KFormPreview/preview.vue";
import { parseItemAuth } from "@/components/TopVUI/bpmn/panel/modal/buttonDialogConfig/helper/index.js";
export default {
  components: {
    KForm,
  },
  computed: {
    isParamError() {
      const error = this.error;
      return error;
    },
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      modelAttrs: {
        title: "表单详情",
        width: 700,
      },
      formOpinion: this.$form.createForm(this),
      drawingList: {},
      error: false,
      description: "",
      initOption: {},
      initParams: {},
      formDetail: {},
      sonSaved: false,
    };
  },
  methods: {
    changeVisible(val) {
      this.visible = val;
    },
    changeLoading(val) {
      this.confirmLoading = val;
    },
    init(option, params) {
      this.changeVisible(true);
      this.initOption = option;
      this.initParams = params;
      if (option.formUuid) {
        let formData = {};
        this.getFormDetailByPuuidAndFormUuid(params.mainUuid, option.formUuid).then(res => {
          const data = res.data || {};
          formData = this.handleFormData(params.mainForm,  data);
          this.formDetail = formData;
          return this.getFormDetail(option.formUuid)
        }).then(() => {
          this.formDetail = formData;
          this.parseDrawingList(formData);
        }).catch((err) => {
          this.error = true;
          this.description = err.message || "操作失败";
          this.$message.warning(err.message || this.description || "操作失败");
        });
      } else {
        this.error = true;
        this.description = "页面参数错误无法正确显示";
      }
    },
    getFormDetail(uuid) {
      return new Promise((resolve, reject) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: uuid,
        })
          .then((res) => {
            if (res.statusCode && res.statusCode != 200) {
              this.error = true;
              this.description = "表单详情获取失败";
              reject();
            } else {
              this.jsonData = res;
              this.error = false;
              this.description = "";
              resolve();
            }
          })
          .catch(() => {
            this.error = true;
            this.description = "表单详情获取失败";
            reject();
          });
      });
    },
    // 解析表单列表
    parseDrawingList(formData) {
      const json = this.jsonData;
      const designJson = json.formDesign.designJson;
      let formList = {};
      try {
        formList = JSON.parse(designJson);
      } catch (e) {
        this.error = true;
        this.drawingList = {};
        this.description = "表单详情解析失败";
        return;
      }
      const formItemConfigs = this.initOption?.formItemConfigs || {};
      const drawingList = this.handleFlowFormData(
        formList,
        formItemConfigs,
        formData
      );
      
      this.drawingList = drawingList;
      this.$refs.formRenderRef &&
        this.$refs.formRenderRef.setData(this.drawingList);
    },
    // 根据puuid获取表单值
    getFormDetailByPuuidAndFormUuid(puuid, formUuid) {
      return new Promise((resolve, reject) => {
        this.$get(`/workflow/flowModel/getForm?slaveUuid=${formUuid}&masterBizUuid=${puuid}`)
          .then((res) => {
            if (res.statusCode && res.statusCode != 200) {
              if(res.message.indexOf("找不到对应数据")) {
                resolve({data: {}})
              }else{
                reject(new Error(res.message || "操作失败"));
              }
            } else {
              resolve(res);
            }
          })
          .catch((err) => {
            reject(new Error("表单数据获取失败"));
          });
      });
    },
    // 表单数据组合
    handleFormData(mainDetail, sonDetail) {
      // 对象合并
      if (sonDetail.uuid) {
        this.sonSaved = true;
        return sonDetail;
      } else {
        this.sonSaved = false;
        return mainDetail;
      }
    },
    // 批量处理流程表单数据
    handleFlowFormData(drawingList, formItemConfigs, formData) {
      const list = drawingList?.list || [];
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        const { model } = element;
        const authCode = formItemConfigs[model];
        const formValue = formData[model] || "";
        const { options } = element;
        parseItemAuth(element, authCode);
        options.defaultValue = formValue;
      }
      return drawingList;
    },
    ok() {
      this.changeLoading(true);
      this.validate().then(res => {
        const { values } = res;
        return this.submit(values)
      }).then(() => {
        this.$emit("ok");
        this.changeVisible(false);
      }).catch(err => {
        this.$message.warning(err.message || "操作失败");
      }).finally(()=> {
        setTimeout(() => {
          this.changeLoading(false); 
        }, 700)
      });
    },
    cancel() {
      this.changeVisible(false);
      this.$emit("cancel");
    },
    validate() {
      return new Promise((resolve, reject) => {
        console.log(this.$refs.formRenderRef, "this.$refs.formRenderRef");
        if(this.$refs.formRenderRef && this.$refs.formRenderRef.getJsonDataForPromise) {
          this.$refs.formRenderRef.getJsonDataForPromise().then(res => {
            resolve(res)
          }).catch(err => {
            reject(new Error("表单验证失败，请检查表单！"))
          })
        }else{
          reject(new Error("组件加载失败，请刷新重试！"))
        }
      })
    },
    getFormData() {
      return this.$refs.formRenderRef && this.$refs.formRenderRef.getFormData()
    },
    // 表单数据提交
    submit(formData) {
      return new Promise((resolve, reject) => {
        const { formUuid } = this.initOption;
        const { mainUuid, mainFormUuid } = this.initParams;
        const params = {
          masterUuid: mainFormUuid,
          slaveUuid: formUuid,
          masterBizUuid: mainUuid,
          data: JSON.stringify(formData),
        }
        this.$post("/workflow/flowModel/updateForm", params).then(res => {
          if (res.statusCode && res.statusCode!= 200) {
            reject(new Error(res.message || "操作失败"));
          }else{
            this.$message.success(res.message || "操作成功");
            resolve();
          }
        }).catch(err => {
          reject(err);
        })  
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.empty-wrap {
  min-height: 500px;
  padding-top: 120px;
}
</style>